package com.core.family.admin.Interceptor;

import com.core.family.admin.domain.dto.SysUserDto;
import com.core.common.utils.JwtUtil;
import com.core.family.admin.service.SysUserService;
import com.core.family.biz.yizhao.domain.dto.YzUserDto;
import com.core.family.biz.yizhao.service.YzUserExtendService;
import com.core.family.springUtils.ApplicationUtil;

/**
 * @program: kuntail
 * @description:
 * @author: honglei
 * @create: 2022-03-30 10:32
 */
public class UserUtil {

    public static final ThreadLocal<SysUserDto> dataContext = new ThreadLocal<>();


    /***
     * 获取用户信息
     * oauth2 应通过 SecurityContextHolder获取
     *
     * @param token
     * @return
     */
    public static SysUserDto setUserInfo(String token) {
        if (!JwtUtil.validateToken(token)) {
            return null;
        }
        String id = JwtUtil.getId(token);
        SysUserService userService = ApplicationUtil.getBean(SysUserService.class);
        SysUserDto sysUserDto = userService.getUserInfo(id);
        dataContext.set(sysUserDto);
        return sysUserDto;
    }



    public static YzUserDto getYzUserDetailByToken(String token){
        if (!JwtUtil.validateToken(token)) {
            return null;
        }
        YzUserExtendService extendService = ApplicationUtil.getBean(YzUserExtendService.class);
        return extendService.getYzUserByToken(token);
    }


    public static SysUserDto getUserInfo(String token) {

        SysUserDto sysUserDto = dataContext.get();
        if (null == sysUserDto) {
            sysUserDto = setUserInfo(token);
        }
        return sysUserDto;
    }

    public static Integer getOrgId() {
        if (null == getUserInfo(null)) {
            return 0;
        }
        return getUserInfo(null).getOrgId();
    }


    public static void remove() {
        dataContext.remove();
    }


}
